package cn.wolfcode.shop.cloud.filter;

import cn.wolfcode.shop.cloud.common.Result;
import cn.wolfcode.shop.cloud.feign.MemberFeignApi;
import cn.wolfcode.shop.cloud.util.CookieUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class CookieRefreshFilter extends ZuulFilter {
    @Autowired
    private MemberFeignApi memberFeignApi;

    @Override
    public String filterType() {
        return FilterConstants.POST_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        //判断用户是否携带了token
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        //获取token
        String userToken = CookieUtil.getCookie(request, "userToken");
        if (userToken != null) {
            return true;
        }
        return false;
    }

    @Override
    public Object run() {
        //如果用户携带了token那么进入到run里面去延长时间
        //延长redis中的key的过期时间和cookie的过期时间
        //判断用户是否携带了token
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        HttpServletResponse response = currentContext.getResponse();
        //获取token
        String userToken = CookieUtil.getCookie(request, "userToken");

        Result<Boolean> result = memberFeignApi.refreshToken(userToken);
        if (result != null && result.getCode() == 200 && result.getData()) {
            //刷新cookie的时间
            CookieUtil.addCookie("userToken", userToken, 1800, response);
        }
        currentContext.setSendZuulResponse(false);
        return null;
    }
}
